package dao.common.imp;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.springframework.orm.hibernate4.HibernateCallback;
import org.springframework.orm.hibernate4.support.HibernateDaoSupport;
import dao.common.MemorandumDao;
import entity.common.Memorandum;
import entity.work.Note;

@SuppressWarnings("unchecked")
public class MemorandumDaoImp extends HibernateDaoSupport implements MemorandumDao{

	@Override
	public boolean save(Memorandum memorandum) {
		this.getHibernateTemplate().save(memorandum);
		return false;
	}

	@Override
	public List<Note> getList(final int startPage, final int pageSize,final String account,final String type) {
		return (List<Note>)this.getHibernateTemplate().execute(new HibernateCallback() {
			@Override
			public Object doInHibernate(Session session)throws HibernateException {
				String hql = "select * from memorandum as model where model.account=:account and model.type=:type order by model.id desc";
				SQLQuery query = session.createSQLQuery(hql);
				query.addEntity(Memorandum.class);
				query.setParameter("account", account);
				query.setParameter("type", type);
				query.setFirstResult(startPage);
				query.setMaxResults(pageSize);
				return query.list();
			}
		});
	}

	@Override
	public int getCount(final String account, final String type) {
	   return this.getHibernateTemplate().execute(new HibernateCallback() {
			@Override
			public Object doInHibernate(Session session) throws HibernateException {
				String hql="select count(*) from memorandum as model where model.account=:account and model.type=:type";
				SQLQuery query = session.createSQLQuery(hql);
				query.setParameter("account", account);
				query.setParameter("type", type);
				String count = query.uniqueResult().toString();
				return Integer.parseInt(count);
			}
		});
	}

	@Override
	public boolean deleteById(final int id, final String account) {
		Object object = (Object) this.getHibernateTemplate().get(Memorandum.class, id);
		this.getHibernateTemplate().delete(object);
		return true;
	}

	@Override
	public boolean update(Memorandum memorandum) {
		this.getHibernateTemplate().update(memorandum);
		return false;
	}

}
